package crane.bomb;

import java.awt.Dimension;
import java.awt.Point;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * @author wangqx
 */
public class BombAction extends ActionAdapter{

    /**
     * constructor
     *
     */
    public BombAction() {
        // do nothing  
    }
    
    /**
     * actStartGame
     */
    protected void actStartGame(MainBean mBean) {
        BombFrame bFrame = mBean.getBombFrame();
        setValueToBean(bFrame);
        clearFrame(mBean.getFrame());
        bFrame.paintFrame(mBean.getFrame());
        bFrame.setBombArray(new BombArray(bFrame.getXLength(), 
                bFrame.getYLength(), 
                bFrame.getLevel()));
        setAllButtonToBean(bFrame);
        bFrame.setMainBean(mBean);
        
        JFrame jframe = mBean.getFrame();
        jframe.pack();
        jframe.setVisible(true);
        jframe.addWindowListener(this);        
        return;
    }
    
    /**
     * setValueToBean
     */
    protected void setValueToBean(BombFrame bombFrame) {
        bombFrame.setXLength(Integer.parseInt(bombFrame.xCombobox.getSelectedItem().toString()));
        bombFrame.setYLength(Integer.parseInt(bombFrame.yCombobox.getSelectedItem().toString()));
        bombFrame.setLevel(Integer.parseInt(bombFrame.levelCombobox.getSelectedItem().toString()));
    }

    /**
     * @param bombFrame
     * @param id
     */
    protected void actLeftButton(BombFrame bombFrame, int id) {
        int xCur = getCurFromId(bombFrame.getYLength(), id, 0);
        int yCur = getCurFromId(bombFrame.getYLength(), id, 1);
        BombBean point = bombFrame.getBombArray().getPoint(xCur, yCur);
        point.open(bombFrame, true);
    }

    /**
     * @param bombFrame
     * @param id
     */
    protected void actRightButton(BombFrame bombFrame, int id) {
        int xCur = getCurFromId(bombFrame.getYLength(), id, 0);
        int yCur = getCurFromId(bombFrame.getYLength(), id, 1);
        BombBean point = bombFrame.getBombArray().getPoint(xCur, yCur);
        point.open(bombFrame, false);
    }

    /**
     * checkGameOvered
     * 
     * @param bombFrame
     * @return boolean
     */
    protected boolean checkGameOvered(BombFrame bombFrame) {
        int finished = isFinished(bombFrame);
        if (finished != 1) {            
            // showDialog("The game is Over!\nPlease restart the game!");
            showModallog(bombFrame.getMainBean().getFrame(), "Message", "The game is Over!\nPlease restart the game!");
            return true;
        }
        return false;
    }
    
    /**
     * showDialog
     * 
     * @param msg
     */
    public void showDialog(String msg) {
        JFrame frame = new JFrame();
        JOptionPane.showMessageDialog(frame, msg);
    }
    
    /**
     * showDialog
     * 
     * @param frame
     * @param title
     * @param msg
     */
    public void showModallog(JFrame frame, String title, String msg) {
        String winTitle = title;
        if (title == null || title.trim() == ""){
            winTitle = "Message";
        }
        JDialog dialog = new ModalWindow(frame, winTitle, msg);
        setDialogStats(frame, dialog);
    }
    
    /**
     * showInputNameWindow
     * 
     * @param mBean
     */
    public void showInputNameWindow(MainBean mBean) {
        JFrame frame = mBean.getFrame();
        BombFrame bFrame = mBean.getBombFrame();
        Map<String, Integer> paramMap = new HashMap<String, Integer>();
        paramMap.put("LEVEL", new Integer(bFrame.getLevel()));
        paramMap.put("TIME", new Integer(bFrame.getScore()));
        BombScoreInputWindow win = new BombScoreInputWindow(frame, paramMap);
        setDialogStats(frame, win);
        
        String name = win.getPlayerName();
        if (name == null || name.trim().length() < 1){
            return;
        }
        
        // Player Score Content
        String[] scoreData = new String[]{
                "" + bFrame.getLevel(),
                name,
                bFrame.getScore()
        };
        saveScore(scoreData);
    }
    
    private void saveScore(String[] playScore){
        XMLUtil util = new XMLUtil();
        util.writeXML(XMLUtil.SCORE_DATA_PATH, playScore);
    }
    
    /**
     * check if Save Score
     * 
     * @param level
     * @param score
     * @return boolean   true: Save;  false: not Save
     */
    protected boolean checkSaveScore(int level, int score){
        XMLUtil util = new XMLUtil();
        List<Integer> scoreList = util.getLevelScore(XMLUtil.SCORE_DATA_PATH, level);
        if (scoreList == null || scoreList.size() < XMLUtil.NUMBER_PER_LEVEL){
            return true;
        }
        Integer maxScore = scoreList.get(scoreList.size() - 1);
        if (score < maxScore.intValue()){
            return true;
        }        
        return false;
    }
    
    /**
     * setDialogStats
     * 
     * @param frame
     * @param dlg
     */
    private void setDialogStats(JFrame frame, JDialog dlg) {
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = frame.getSize();
        Point loc = frame.getLocation();
        dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setModal(true);
        dlg.pack();
        dlg.setVisible(true);
    }
    
    /**
     * change Start Button's Image
     * 
     * @param bombFrame
     * @param path
     */
    protected void changeStartButtonImage(BombFrame bombFrame, String path){
        bombFrame.startButton.setIcon(FileUtil.getImage(path));
    }

    /**
     * @param id
     * @param flag
     * @param yLen
     * @return cur
     */
    protected int getCurFromId(int yLen, int id, int flag) {
        int x = new Double(id / yLen).intValue();
        if (flag == 1) {
            return id - x * yLen;
        } else {
            return x;
        }
    }

    /**
     * setAllButtonToBean
     * @param bombFrame
     */
    protected void setAllButtonToBean(BombFrame bombFrame) {
        
        int xCur = 0;
        int yCur = 0;
        int xLen = bombFrame.getXLength();
        int yLen = bombFrame.getYLength();
        BombBean[][] pa = bombFrame.getBombArray().getPointArray();
        for (int i = 0; i < xLen * yLen; i++) {
            xCur = getCurFromId(yLen, i, 0);
            yCur = getCurFromId(yLen, i, 1);
            BombBean pb = pa[xCur][yCur];
            pb.setButton(bombFrame.getButton(i));
        }
    }

    /**
     * setBombed
     * @param bombFrame
     */
    public void setBombed(BombFrame bombFrame) {

        int xCur = 0;
        int yCur = 0;
        JButton button = null;
        int xLen = bombFrame.getXLength();
        int yLen = bombFrame.getYLength();
        BombArray ba = bombFrame.getBombArray();
        BombBean[][] pa = ba.getPointArray();
        for (int i = 0; i < xLen * yLen; i++) {
            xCur = getCurFromId(yLen, i, 0);
            yCur = getCurFromId(yLen, i, 1);
            BombBean pb = pa[xCur][yCur];
            button = bombFrame.getButton(i);
            if (pb.isOpen()){
                continue;
            }
            if (pb.isBomb() && !pb.isAsBomb()) {
                button.setBackground(BombColor.C_BTN_BOMBED);
                button.setIcon(FileUtil.getImage("/images/bomb.gif"));
            } else if (pb.isBomb() && pb.isAsBomb()){
                button.setBackground(BombColor.C_BTN_CLOSING_BOMBED);
                button.setIcon(FileUtil.getImage("/images/asBomb.gif"));
            }
        }
        ba.setBombed(true);
        changeStartButtonImage(bombFrame, "/images/9.gif");
    }
    
    /**
     * check is it Finished
     * 
     * @param bombFrame
     * @return int(-1: bombed; 0: finished; 1: not yet)
     */
    protected int isFinished(BombFrame bombFrame){
        BombArray ba = bombFrame.getBombArray();
        if (ba.isBombed()){
            return -1;
        }
        int xLen = bombFrame.getXLength();
        int yLen = bombFrame.getYLength();
        int opened = BombArray.CHECKED_POINT_MAP.size();
        if (opened + ba.getBombNum() == xLen * yLen &&
                ba.getBombRemain() == 0){
            return 0;
        }
        return 1;
    }
    
    /**
     * clear Frame
     */
    protected void clearFrame(JFrame frame) {
        if (frame == null || frame.getComponentCount() == 0){
            return;
        }
        frame.getContentPane().removeAll();
    }
    
    
    /**
     * create String[]
     * @param min
     * @param max
     * @return String[]
     */
    protected String[] createArray(int min, int max){

        String[] newArray = new String[max - min + 1];
        int value = min;
        for (int i = 0; i < newArray.length; i++) {
            newArray[i] = String.valueOf(value);
            value++;
        }
        return newArray;
    }

}
